<?php
namespace common\services\budget;

use common\entities\ConfigEntity;
use common\entities\ContractEntity;
use common\error\ReturnErrorTrait;
use common\repositories\budget\BudgetRepository;
use common\services\BaseService;
use common\services\common\MyscrmApplicationService;

/**
 * Created by PhpStorm.
 * User: silenceper
 * Date: 16/9/9
 * Time: 上午11:42
 */
class BudgetService extends BaseService {

    private $_budgetRepository;

    //对应应用
    private static $applicationCode = [
        5002 => "移动销售",
        5024 => "人脸识别",
        5023 => "来访登记",
        5003 => "渠道管家",
        5010 => "云行销",
        5020 => "秒杀活动",
        "kmcb" => "快码传播",
        5025 => "到访传播",
        5027 => "在线开盘",
    ];

    private static $freeApplicationCodes = [
        5009 => "微楼书(新版)",
        5001 => "微楼书",
        5030 => "云Call客",
        5008 => "小蜜蜂",
        5021 => "认筹理财",
    ];

    public function __construct(BudgetRepository $budgetRepository, $config = [])
    {
        $this->_budgetRepository = $budgetRepository;
        parent::__construct($config);
    }

    /**
     * 预算列表
     */
    public function getList()
    {
        $result = [];
        $hasThisYearData = false;

        //整理格式
        $dataList = $this->_budgetRepository->getAllList(array_keys(self::$freeApplicationCodes));
        if($dataList){
            $allData = [];

            foreach ($dataList as $budget){
                $allData[$budget['year']][$budget['appCode']][$budget['month']] = $budget['money'];
            }

            foreach ($allData as $year => $appValue){

                if (!$hasThisYearData && $year == date("Y")) {
                    $hasThisYearData = true;
                }

                $yearArr = [];
                $yearArr['year'] = $year;
                $yearArr['detail'] = [];

                foreach($appValue as $appCode => $monthValue){
                    $appArr = [];
                    $appArr['total'] = 0;
                    $appArr['appCode'] = $appCode;
                    $appArr['appName'] = self::$applicationCode[$appCode];

                    foreach($monthValue as $month => $value){
                        $appArr[$month] = $value;
                        $appArr['total'] += $value;
                    }

                    $yearArr['detail'][] = $appArr;
                }

                //排序
                $yearArr['detail'] = $this->arraySort($yearArr['detail']);

                $result[] = $yearArr;
            }
        }

        if (!$hasThisYearData) {
            $year = date("Y");
            //没有今年的数据,手动新增一条
            $thisYearData = [];

            $thisYearData["year"] = $year;
            $thisYearData["detail"] = [];
            foreach (self::$applicationCode as $code => $appName) {
                $subItem = ["appCode" => $code, "appName" => $appName, "total" => 0];
                for ($i = 1; $i <= 12; $i++) {
                    $subItem[$i] = 0;
                }
                array_push($thisYearData["detail"], $subItem);
            }
            array_unshift($result, $thisYearData);
        }

        return $result;
    }

    private function arraySort($arr)
    {
        if (!empty($arr)) {

            $sortTemp = [];
            $i = 1;
            foreach (self::$applicationCode as $code => $appName) {
                $sortTemp[$code] = $i;
                $i++;
            }

            $tmp = [];
            foreach ($arr as $item) {
                $tmp[$sortTemp[$item['appCode']]] = $item;
            }

            ksort($tmp);

            return array_values($tmp);

        }

        return $arr;
    }


    /**
     * 数据保存
     * @param $year
     * @param $data
     * @return bool
     */
    public function save($year, $data)
    {
        //先删后插
        if($data){

            $trans = ContractEntity::getDb()->beginTransaction();
            try{

                $deleteRuslt = $this->deleteBudgetByYear($year);
                if($deleteRuslt === false){
                    $trans->rollBack();
                    return $this->setAndReturn(__LINE__, '删除数据出错');
                }

                $addRuslt = $this->addBudget($year, $data);
                if($addRuslt === false){
                    $trans->rollBack();
                    return $this->setAndReturn(__LINE__, '插入数据出错');
                }

                $trans->commit();
                return true;
            }catch (\Exception $e){
                $trans->rollBack();
                \Yii::error((string)$e);
                return $this->setAndReturn(__LINE__, '保存数据出错');
            }

        }

        return true;
    }

    public function deleteBudgetByYear($year)
    {
        return $this->_budgetRepository->deleteBudgetByYear($year);
    }

    public function addBudget($year, $data)
    {
        return $this->_budgetRepository->addBudget($year, $data);
    }
}